package com.example.element.module.permission

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.common.base.AbsActivity
import com.example.element.R
import com.example.element.databinding.ActPermissionHomeBinding
import kotlinx.android.synthetic.main.act_permission_home.*

@Route(path = "/permission/home")
class PermissionActivity : AbsActivity<ActPermissionHomeBinding>() {

    private val permissionCallPhone = "Manifest.permission.CALL_PHONE"

    override fun getLayoutId() = R.layout.act_permission_home


    override fun main() {

    }

    override fun initListener() {
        btn_phone.setOnClickListener {
            //判断权限
            if (ContextCompat.checkSelfPermission(mContext, permissionCallPhone) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CALL_PHONE), 100)
            } else {
                call()
            }
        }

    }

    private fun call() {
        val intent = Intent(Intent.ACTION_CALL)
        intent.data = Uri.parse("tel:10086")
        startActivity(intent)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            100 -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    call()
                } else {
                    Toast.makeText(mContext, "You denied the permission", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}